package com.issac.filter;

import com.issac.common.Const;
import com.issac.exception.CaptchaException;
import com.issac.handler.LoginFailureHandler;
import com.issac.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName CaptchaFilter
 * @Author zy
 * @Date 2021/12/13 11:32
 * @Description CaptchaFilter 继承OncePerRequestFilter能够确保在一次请求只通过一次filter，而不需要重复执行。
 * @Version 1.0
 */
@Component
public class CaptchaFilter extends OncePerRequestFilter {
    private final String loginUrl = "/login";

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String url = request.getRequestURI();
        if (url.equals(loginUrl) && request.getMethod().equals("POST")) {
            try {
                validate(request);
            } catch (CaptchaException e) {
                e.printStackTrace();
                loginFailureHandler.onAuthenticationFailure(request,response,e);
            }
        }
        chain.doFilter(request,response);
    }

    private void validate(HttpServletRequest request) {
        String code = request.getParameter("code");
        String key = request.getParameter("key");
        if (StringUtils.isBlank(code) || StringUtils.isBlank(key)) {
            throw new CaptchaException("验证码不能为空");
        }

        if (!code.equals(redisUtil.hget(Const.KAPTCHA_KEY, key))) {
            throw new CaptchaException("验证码输入错误");
        }

        // 一次性使用
        redisUtil.hdel(Const.KAPTCHA_KEY,key);
    }
}
